package com.scpii.universal.pns.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.doone.comm.paginaction.Pagination;
import com.scpii.universal.action.BaseAction;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.pns.dto.MessageDto;
import com.scpii.universal.pns.dto.MessgeBodyDto;
import com.scpii.universal.pns.dto.MsgManageDto;
import com.scpii.universal.pns.entity.PnsGroup;
import com.scpii.universal.pns.entity.PnsMessage;
import com.scpii.universal.pns.entity.PnsUser;
import com.scpii.universal.pns.service.PnsMessageService;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;
import com.scpii.universal.util.StreamUtil;
import com.scpii.universal.util.UtilTool;

@Controller
@Scope("prototype")
public class PnsMessageAction extends BaseAction {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 640376469611095221L;
	@Resource
	private PnsMessageService pnsMessageService;
	// 查询用户
	private PnsUser condition;
	// 添加组
	private PnsGroup pnsGroup;
	// 选择的用户Id集合
	private String userIds;
	// 选择的组集合
	private String groupIds;
	
	private Integer messageId;
	// 内容信息
	private MessageDto msgDto;

	List<MsgManageDto> msgList;

	private File fileMaterial;// Ajax获取图片文件,与控件type=File中的name属性一样
	private String fileMaterialFileName;// Ajax获取图片文件名称,相应的name属性名称+FileName
	private Pagination page = new Pagination();
	HttpServletResponse response = ServletActionContext.getResponse();
	HttpServletRequest request = ServletActionContext.getRequest();
	private int enterpId = UtilTool.ObjectToInteger(request.getSession().getAttribute("enterpId"));
	private String fromUrl;
	private List<PnsGroup> groupInfo;
	private String uploadPath;

	/**
	 * 页面初始化加载
	 * 
	 * @param request
	 * @param response
	 */
	public String getPnsInit() {
		//初始化
		String absolutePath = getWebAppsRealPath() + getImgBasePath()+ ImgAndFilePath.PNS;
		File file = new File(absolutePath);
		if(!file.exists()) {
			file.mkdirs();
		}

		// 获取以前的messge信息

		if (getSelectPerPage("page") == -1) {
			page.setPageRecord(GenericConstants.PAGE_NO);
		} else {
			page.setPageRecord(getSelectPerPage("page"));
		}
		// 判断是否是第一次查询
		if (getQueryFlag("page") == -1) {
			page.setTotalRecord(pnsMessageService.getMessgetCount(enterpId, getUserInfo().getAppId()));
		} else {
			page.setTotalRecord(getQueryFlag("page"));
		}
		setPageParameters(page, "page");
		msgList = pnsMessageService.getPnsManage(enterpId, page.getCurrentPage(), page.getPageRecord(), getUserInfo().getAppId());
		return SUCCESS;

	}

	public String addPnsMessage() throws IllegalAccessException, InvocationTargetException {
		if ("edit".equals(fromUrl)) {
			PnsMessage msg = pnsMessageService.get(Integer.parseInt(request.getParameter("id")));
			msg.setIcon("default".equals(msg.getIcon())?msg.getIcon():getServerURL()+msg.getIcon());
			msgDto = new MessageDto();
			BeanUtils.copyProperties(msgDto, msg);
			msgDto.msgBodyToList();
		}
		return SUCCESS;
	}

	/**
	 * 获取目标用户群体的信息
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public String getTargetUserGroupInfo() {
		try {
			List<PnsUser> userList = pnsMessageService.getUserinfo(condition, 0, 0, getUserInfo().getAppId());
			// 设置编码格式
			response.setCharacterEncoding("utf-8");
			// 将数据转换成前台js array格式的数据
			JSONObject data = new JSONObject();
			data.put("userList", userList);

			response.getWriter().print(data.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 保存新建的推送消息 目标组
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public String saveGroupInfo() throws IOException {
		Integer count = pnsMessageService.saveGroupInfo(pnsGroup, userIds,getUserInfo().getAppId());
		response.getWriter().print(count);
		return null;
	}

	/**
	 * 保存推送信息
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public String saveMessageInfo()  {

		try {
			messageId=pnsMessageService.saveMessageInfo(msgDto, request, groupIds, enterpId, getUserInfo().getAppId(),getImgBasePath());
		} catch (Exception e) {			
			e.printStackTrace();
		}

		return SUCCESS;
	}
	/**
	 * 保存组合message的关系
	 * @return
	 * @author zhangqiang
	 * 2012-11-28上午10:56:53
	 */
	public String saveMsgGroup(){
		pnsMessageService.saveMsgGroup(messageId,enterpId, getUserInfo().getAppId());
		return SUCCESS;
	}

	/**
	 * 通过Ajax获取图片信息
	 * 
	 * @return
	 * @throws IOException
	 */
	public String ajaxGetImage() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		if (fileMaterial != null) {
			String absolutePath = getWebAppsRealPath();
			if (uploadPath != null){
				absolutePath = absolutePath + getImgBasePath() +  File.separator + uploadPath;
			} else {
				absolutePath = absolutePath + ImgAndFilePath.TEMP_FOLDER;
			}
			File file = new File(absolutePath);
			if(!file.exists()) {
				file.mkdirs();
			}
			String filePath = absolutePath + File.separator +FileUploadUtil.generateIconName() + ".png";

			String serverPath = StreamUtil.uploadActiveImgs(fileMaterial, filePath).replace(getWebAppsRealPath(), "").replaceAll("\\\\", "/");
			response.getWriter().print("图片#" + serverPath + "#上传成功!");// 把相应的地址放到前台解析，通过#符号分割
		} else {
			response.getWriter().print("图片上传失败!");
		}
		return null;
	}

	public String goAddGroup() {
		try {
			messageId=pnsMessageService.saveMessageInfo(msgDto, request, groupIds, enterpId, getUserInfo().getAppId(),getImgBasePath());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "next";
	}

	/**
	 * 异步删除组名
	 * 
	 * @return
	 * @author zhangqiang 2012-11-27下午03:45:12
	 * @throws UnsupportedEncodingException 
	 */
	public String delGroup() throws UnsupportedEncodingException {
		pnsMessageService.delgroupByName(pnsGroup);
		try {
			response.getWriter().print(1);
		} catch (IOException e) {			
			e.printStackTrace();
		}
		return null;
	}
	
	public String editMessageGroup() {
		this.setGroupInfo(pnsMessageService.getGroupByMessageId(getUserInfo().getAppId(), messageId));
		return SUCCESS;
	}
	
	/**
	 * 确认可以发送消息
	 * 
	 * @return
	 */
	public String editMessgeStatus() {
		pnsMessageService.updateMessageStatus(messageId);
		return null;
	}

	public PnsUser getCondition() {
		return condition;
	}

	public void setCondition(PnsUser condition) {
		this.condition = condition;
	}

	public PnsGroup getPnsGroup() {
		return pnsGroup;
	}

	public void setPnsGroup(PnsGroup pnsGroup) {
		this.pnsGroup = pnsGroup;
	}

	public String getUserIds() {
		return userIds;
	}

	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}

	public String getGroupIds() {
		return groupIds;
	}

	public void setGroupIds(String groupIds) {
		this.groupIds = groupIds;
	}

	public MessageDto getMsgDto() {
		return msgDto;
	}

	public void setMsgDto(MessageDto msgDto) {
		this.msgDto = msgDto;
	}

	public File getFileMaterial() {
		return fileMaterial;
	}

	public void setFileMaterial(File fileMaterial) {
		this.fileMaterial = fileMaterial;
	}

	public String getFileMaterialFileName() {
		return fileMaterialFileName;
	}

	public void setFileMaterialFileName(String fileMaterialFileName) {
		this.fileMaterialFileName = fileMaterialFileName;
	}

	public Pagination getPage() {
		return page;
	}

	public void setPage(Pagination page) {
		this.page = page;
	}

	public List<MsgManageDto> getMsgList() {
		return msgList;
	}

	public void setMsgList(List<MsgManageDto> msgList) {
		this.msgList = msgList;
	}

	public Integer getMessageId() {
		return messageId;
	}

	public void setMessageId(Integer messageId) {
		this.messageId = messageId;
	}

	public String getFromUrl() {
		return fromUrl;
	}

	public void setFromUrl(String fromUrl) {
		this.fromUrl = fromUrl;
	}

	public List<PnsGroup> getGroupInfo() {
		return groupInfo;
	}

	public void setGroupInfo(List<PnsGroup> groupInfo) {
		this.groupInfo = groupInfo;
	}

	public String getUploadPath() {
		return uploadPath;
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

}
